package com.corpgovernment.job.service;

import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.job.controller.vo.jobtype.CreateJobTypeReqVo;
import com.corpgovernment.job.controller.vo.jobtype.DeleteJobTypeReqVo;
import com.corpgovernment.job.controller.vo.jobtype.ListAllJobTypeRespVo;
import com.corpgovernment.job.controller.vo.jobtype.UpdateJobTypeReqVo;
import com.corpgovernment.job.dao.dataobject.CountDo;
import com.corpgovernment.job.dao.entity.db.JobDo;
import com.corpgovernment.job.dao.entity.db.JobTypeDo;
import com.corpgovernment.job.dao.mapper.JobMapper;
import com.corpgovernment.job.dao.mapper.JobTypeMapper;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ldma
 * @date 2024/1/2
 */
@Service
@Slf4j
public class JobTypeService {

    @Resource
    private JobTypeMapper jobTypeMapper;
    @Resource
    private JobMapper jobMapper;
    @Autowired
    private TransactionTemplate transactionTemplate;

    public void createJobType(CreateJobTypeReqVo requestParam) {
        // 前置校验
        StringBuilder sb = new StringBuilder();
        // 岗位类型名称
        checkJobTypeName(requestParam.getJobTypeName(), null, sb);
        // 岗位类型编号
        checkJobTypeCode(requestParam.getJobTypeCode(), null, sb);
        String errorMsg = sb.toString();
        if (StringUtils.isNotBlank(errorMsg)) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.CHECK_ERROR.code(), errorMsg.substring(0, errorMsg.length()-1));
        }
        // 保存岗位类型
        jobTypeMapper.create(new JobTypeDo(requestParam.getJobTypeName(), requestParam.getJobTypeCode()));
    }

    public void deleteJobType(DeleteJobTypeReqVo requestParam) {
        Long jobTypeId = requestParam.getJobTypeId();
        if (jobTypeId == null) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.CHECK_ERROR);
        }
        transactionTemplate.execute(status -> {
            // 删除岗位类型
            jobTypeMapper.removeById(jobTypeId);
            // 岗位类型下岗位归类到未分类
            jobMapper.updateJobTypeToUnclassified(jobTypeId);
            return null;
        });
    }

    public void updateJobType(UpdateJobTypeReqVo requestParam) {
        // 前置校验
        StringBuilder sb = new StringBuilder();
        // 岗位类型id
        Long jobTypeId = requestParam.getJobTypeId();
        if (jobTypeId == null) {
            sb.append("岗位类型id为空；");
        } else {
            // 岗位类型名称
            checkJobTypeName(requestParam.getJobTypeName(), jobTypeId, sb);
            // 岗位类型编号
            checkJobTypeCode(requestParam.getJobTypeCode(), jobTypeId, sb);
        }
        String errorMsg = sb.toString();
        if (StringUtils.isNotBlank(errorMsg)) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.CHECK_ERROR.code(), errorMsg.substring(0, errorMsg.length()-1));
        }
        // 更新岗位类型
        jobTypeMapper.update(new JobTypeDo(requestParam.getJobTypeId(), requestParam.getJobTypeName(), requestParam.getJobTypeCode()));
    }

    public ListAllJobTypeRespVo listAllJobType() {
        ListAllJobTypeRespVo result = new ListAllJobTypeRespVo();
        // 查询所有岗位类型
        List<JobTypeDo> jobTypeDoList = jobTypeMapper.listAll();
        if (CollectionUtils.isEmpty(jobTypeDoList)) {
            return result;
        }
        // 查询所有岗位类型对应的岗位数
        Map<Long, Integer> jobCountMap = jobMapper.listAll().stream().collect(Collectors.groupingBy(JobDo::getJobTypeId, Collectors.summingInt(item -> 1)));
        int jobCount = jobCountMap.values().stream().mapToInt(Integer::intValue).sum();
        // 组装返回结果
        List<ListAllJobTypeRespVo.JobType> jobTypeList = new ArrayList<>(jobTypeDoList.size());
        jobTypeDoList.forEach(jobTypeDo -> jobTypeList.add(new ListAllJobTypeRespVo.JobType(jobTypeDo, jobCountMap)));
        // 变成树结构
        result.setJobTypeTree(Collections.singletonList(new ListAllJobTypeRespVo.JobType(null, "全部", "", jobCount, jobTypeList)));
        return result;
    }

    private void checkJobTypeCode(String jobTypeCode, Long jobTypeId, StringBuilder sb) {
        if (StringUtils.isNotBlank(jobTypeCode)) {
            if (jobTypeCode.length() > 20) {
                sb.append("岗位类型编号超过20个字符；");
            }
            JobTypeDo jobTypeDo = jobTypeMapper.getByCode(jobTypeCode);
            if (jobTypeDo != null && !jobTypeDo.getId().equals(jobTypeId)) {
                sb.append("岗位类型编号不唯一；");
            }
        }
    }

    private void checkJobTypeName(String jobTypeName, Long jobTypeId, StringBuilder sb) {
        if (StringUtils.isBlank(jobTypeName)) {
            sb.append("岗位类型名称为空；");
        } else {
            if (jobTypeName.length() > 20) {
                sb.append("岗位类型名称超过20个字符；");
            }
            JobTypeDo jobTypeDo = jobTypeMapper.getByName(jobTypeName);
            if (jobTypeDo != null && !jobTypeDo.getId().equals(jobTypeId)) {
                sb.append("岗位类型名称不唯一；");
            }
        }
    }

}
